import React, { useState, useEffect, useRef } from "react";
import style from "./style.less";
import image from "assets/images/person.png";
export default () => {
  const ref = useRef();
  const contentRef = useRef();
  const [data, setData] = useState([]);

  const [top, setTop] = useState(0);
  let fullPage = 4;// 滚动的页数
  const getData = () => {
    let list = [];
    let t = Math.round(Math.random() * 5000);
    for (let i = 0; i < 12; i++) {
      list.push({ name: `第${t}次我是好人${i}`, value: t });
    }
    setData(list);
  };
  /* ========= 定时获取数据 ======== */
  useEffect(() => {
    getData();
    let timer = setInterval(() => {
      getData();
    }, 12000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  /* 实时改变内容容器的top值，通过transition 来过渡 */
  useEffect(() => {
    let h = ref.current.offsetHeight;
    let timer = setInterval(() => {
      setTop((t) => {
        if (-h * (fullPage - 1) >= t) {
          contentRef.current.style.cssText = "transition:none";
          return 0;
        } else {
          contentRef.current.style.cssText = "transition:top 0.3s linear ";
          return t - h;
        }
      });
    }, 3000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className={style.box_wrap}>
      {/* 头部 */}
      <div className={style.top_box}>
        <div className={`flex_value1 ${style.top_item}`}><p className={style.first}>2</p></div>
        <div className={`flex_value1 ${style.top_item}`}><p className={style.secord}>1</p></div>
        <div className={`flex_value1 ${style.top_item}`}><p className={style.third}>3</p></div>
      </div>
      {/* 底部 */}
      <div className={style.bottom_box} ref={ref}>
        <ul className={style.content} style={{ top }} ref={contentRef}>
          {data.map((e, index) =>
            (
              <li key={index} className={style.item} style={{ height: `${100 / 3 }%` }}>
                <div className={`flex_value2 ${style.left}`}>
                  <span>{index + 1}</span>
                  <img src={image} alt="明星头像" />
                  <label>萧敬腾</label>
                </div>
                <div className={`${style.right} flex_value1`}>
                  {e.value}
                </div>
              </li>))}
        </ul>
      </div>
    </div>
  );
};
